﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@


@{
    ViewBag.Title = "Bom修改";
    Layout = null;
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bom工单</title>
    <!-- 引用Layui的CSS -->
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        /* 整体表单容器样式 */
        .order-form-container {
            padding: 10px;
        }
        /* 表单行样式 */
        .form-row {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }
        /* 操作按钮容器样式 */
        .operation-buttons {
            text-align: right;
            margin-bottom: 10px;
        }
        /* 表格样式 */
        .layui-table {
            width: 100%;
        }
        /* 标签样式 */
        label {
            width: 120px; /* 统一标签宽度 */
            text-align: right;
            margin-right: 10px;
            white-space: nowrap; /* 防止字段名换行 */
        }
        /* 输入框样式 */
        input {
            width: 200px; /* 修改输入框宽度为350px */
        }
        /* 文本域样式 */
        textarea {
            width: 350px;
            min-height: 50px; /* 设置文本域最小高度 */
        }
    </style>
</head>

<body>
    <div class="order-form-container">
        <!-- 操作按钮 -->
        <div class="operation-buttons">
            <button class="layui-btn" id="saveButton">保存</button>
        </div>
        <!-- 表单信息 -->
        <div class="form-row">
            <label>BOM编号:</label>
            <input type="text" id="bomCode" disabled placeholder="后端自动生成">
            <label>BOM主题:</label>
            <input type="text" id="bomTheme" placeholder="请输入主题">
        </div>
        <div class="form-row">
            <label>默认BOM:</label>
            <select id="documentCode">
                <option value="是">是</option>
                <option value="否">否</option>
            </select>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp &nbsp &nbsp;&nbsp;
            <label>版本:</label>
            <input type="text" id="bomVersion" placeholder="请输入版本">
        </div>
        <div class="form-row">
            <label>成品类型:</label>
            <select id="productType">
                <option value="类型一">类型一</option>
                <option value="类型二">类型二</option>
                <option value="类型三">类型三</option>
            </select>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;
            <label>成品名称:</label>
            <input type="text" id="productName" placeholder="请输入成品名称">
        </div>
        <div class="form-row">
            <label>日产量:</label>
            <input type="text" id="ProductionNum" placeholder="请输入日产量">
        </div>
        <div class="form-row">
            <label>备注:</label>
            <textarea id="remark"></textarea> <!-- 将备注改为文本域 -->
        </div>

        <!-- 表单信息表格操作按钮 -->
        <div class="form-row">
            <button class="layui-btn layui-btn-xs" id="addMaterialButton">新增物料</button>
        </div>
        <!-- 表单信息表格 -->
        <table class="layui-table" id="materialTable">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>型号规格</th>
                    <th>单位</th>
                    <th>品牌</th>
                    <th>配件数量</th>
                    <th>损耗率</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>
        layui.use(['layer', 'form', 'jquery'], function () {
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.jquery;

            // 初始化一个空行
            function initEmptyRow() {
                return {
                    partsCode: '',
                    partsName: '',
                    partsType: '',
                    partsUnit: '',
                    partsBrand: 0,
                    partsNum: 0,
                    partsLoss: '',
                };
            }

            // 添加物料行
            function addMaterialRow(material) {
                console.log('Adding row with material:', material); // 添加调试语句
                material = material || initEmptyRow();
                var rowCount = $('#materialTable tbody tr').length + 1;

                var rowHtml =
                    `<tr data-index="${rowCount - 1}">
                                       <td>
                                          ${rowCount}
                                        </td>
                                        <td>
                                           <input type="text" class="layui-input partsCode" value="${material.partsCode}" id="partsCode" placeholder="物料编码(后端自动生成)" readonly>
                                        </td>
                                        <td>
                                        <input type="text" class="layui-input partsName" value="${material.partsName}" id="partsName" placeholder="物料名称">
                                        </td>
                                          <td>
                                         <input type="text" class="layui-input" value="${material.partsType}" id="color" placeholder="型号规格">
                                         </td>
                                         <td>
                                             <select class="layui-select partsUnit" id="partsUnit">
                                               <option value="台" ${material.partsUnit === '台' ? 'selected' : ''}>台</option>
                                               <option value="箱" ${material.partsUnit === '箱' ? 'selected' : ''}>箱</option>
                                                <option value="瓶" ${material.partsUnit === '瓶' ? 'selected' : ''}>瓶</option>
                                                  </select>
                                                  </td>
                                          <td>
                                             <select class="layui-select partsBrand" id="partsBrand">
                                               <option value="1" ${material.partsBrand === '五毒牌' ? 'selected' : ''}>五毒牌</option>
                                               <option value="2" ${material.partsBrand === '混合牌' ? 'selected' : ''}>混合牌</option>
                                               <option value="3" ${material.partsBrand === '清新牌' ? 'selected' : ''}>清新牌</option>
                                             </select>
                                          </td>
                                           <td>
                                           <input type="number" class="layui-input partsNum" id="partsNum" value="${material.partsNum}" placeholder="配件数量">
                                           </td>
                                            <td>
                                             <input type="text" class="layui-input partsLoss" id="partsLoss" value="${material.partsLoss}" placeholder="损耗率">
                                            </td>
                                            <td><button type="button" class="layui-btn layui-btn-xs layui-btn-danger deleteMaterialButton">删除</button></td>
                    </tr>`;

                $('#materialTable tbody').append(rowHtml);
                form.render();
            }

            // 初始化一个空行
            addMaterialRow();

            // 新增物料按钮点击事件
            $('#addMaterialButton').click(function () {
                addMaterialRow();
            });

            // 删除物料按钮点击事件
            $(document).on('click', '.deleteMaterialButton', function () {
                var $tr = $(this).closest('tr');
                layer.confirm('确定删除该物料吗？', function (index) {
                    $tr.remove();
                    // 重新编号
                    $('#materialTable tbody tr').each(function (index) {
                        $(this).find('td:first').text(index + 1);
                    });
                    layer.msg('物料已删除', { icon: 1 });
                });
            });

            // 从localStorage中获取BomCode
            var bomCode = localStorage.getItem('BomCode');
            if (bomCode) {
                // 发送AJAX请求
                $.ajax({
                    //url: 'http://localhost:5234/api/WorkOrder/ReverseBom',
                    url: "@ViewBag.BaseUrl/T7/WorkOrder/ReverseBom",

                    type: 'GET',
                    data: { BomCode: bomCode },
                    dataType: 'json',
                    success: function (res) {
                        if (res && res.data) {
                            var data = res.data;
                            console.log('接口返回数据:', data);
                            console.log('bomParts:', data.bomParts); // 添加调试语句

                            // 反填数据到表单字段
                            $('#bomCode').val(data[0].bomCode);
                            $('#bomTheme').val(data[0].bomTheme);
                            $('#documentCode').val(data[0].defaultBom === '是' ? '是' : '否');
                            $('#bomVersion').val(data[0].bomVersion);
                            $('#productType').val(data[0].productType);
                            $('#productName').val(data[0].productName);
                            $('#ProductionNum').val(data[0].productionNum);
                            $('#remark').val(data[0].remarks);

                            // 处理表格数据
                            var bomParts = data[0].bomParts;
                            if (Array.isArray(bomParts)) {
                                $('#materialTable tbody').empty();
                                bomParts.forEach(function (part, index) {
                                    var partsCode = part.partsCode;
                                    var partsName = part.partsName;
                                    var partsType = part.partsType;
                                    var partsUnit = part.partsUnit;
                                    var partsBrand = part.partsBrand;
                                    var partsNum = part.partsNum;
                                    var partsLoss = part.partsLoss;

                                    var material = {
                                        partsCode: partsCode,
                                        partsName: partsName,
                                        partsType: partsType,
                                        partsUnit: partsUnit,
                                        partsBrand: partsBrand,
                                        partsNum: partsNum,
                                        partsLoss: partsLoss
                                    };
                                    addMaterialRow(material);
                                });
                            }
                            form.render();
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error(xhr.responseText);
                    }
                });
            }

            // 保存按钮点击事件
            $('#saveButton').click(function () {
                var currentUser = localStorage.getItem('userData');
                var currentDate = new Date();
                var formData = {
                    bomCode: $('#bomCode').val(),
                    defaultBom: $('#documentCode').val(),
                    productType: $('#productType').val(),
                    productName: $('#productName').val(),
                    remarks: $('#remark').val(),
                    productionNum: $('#ProductionNum').val(),
                    bomTheme: $('#bomTheme').val(),
                    bomVersion: $('#bomVersion').val(),
                    bomVersion: $('#bomVersion').val(),
                    estimatedCost: "8000",
                    updateName:currentUser,
                    updateDate: currentDate,
                    bomParts: []
                };

                // 收集物料数据
                $('#materialTable tbody tr').each(function () {
                    var $tr = $(this);
                    var material = {
                        bomCode: $('#bomCode').val(),
                        partsCode: $tr.find('.partsCode').val(),
                        partsName: $tr.find('.partsName').val(),
                        partsType: $tr.find('#color').val(),
                        partsUnit: $tr.find('.partsUnit').val(),
                        partsBrand: parseFloat($tr.find('.partsBrand').val()),
                        partsNum: parseFloat($tr.find('.partsNum').val()),
                        partsLoss: $tr.find('.partsLoss').val(),
                    };
                    formData.bomParts.push(material);
                });

                if (formData.bomParts.length === 0) {
                    layer.msg('请至少添加一个物料', { icon: 2 });
                    return;
                }

                // 发送AJAX请求到更新接口
                $.ajax({
                    //url: 'http://localhost:5090/api/WrokOrder/UpdateBom',
                    url: "@ViewBag.BaseUrl/T7/WrokOrder/UpdateBom",
                    type:'Put',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function (res) {
                        layer.msg('修改成功', { icon: 1, time: 2000 }, function () {
                            location.href = "/WorkOrder/GetBOM";
                        });
                    },
                    error: function (xhr, status, error) {
                        layer.msg('修改失败: ' + error, { icon: 2 });
                        console.error(xhr.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>    